﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Netfraction
{
    public class ChatWindowManager
    {
        private Dictionary<Netfraction.Identity, ChatWindow> chatWindows;
        public delegate void ChatWindowClosedDelegate(Netfraction.Identity remoteIdentity);
        public static event ChatWindowClosedDelegate ChatWindowClosed;

        public ChatWindowManager()
        {
            chatWindows = new Dictionary<Netfraction.Identity, ChatWindow>();
            ChatWindowClosed += new ChatWindowClosedDelegate(ChatWindowManager_ChatWindowClosed);
        }

        void ChatWindowManager_ChatWindowClosed(Netfraction.Identity remoteIdentity)
        {
            chatWindows.Remove(remoteIdentity);
        }

        public void DisplayMessage(Netfraction.RemoteMachine.Hub hub, Netfraction.Identity localIdentity, Netfraction.Identity remoteIdentity, string message, bool localUserSending)
        {
            ChatWindow chat = GetChatWindowByRemoteClientId(remoteIdentity.ClientId);
            if (chat != null)
            {
                    chat.DisplayMessage(localUserSending ? localIdentity : remoteIdentity, message);
            }
            else
            {
                if (message != null)
                {
                    chat = new ChatWindow(hub, localIdentity, remoteIdentity, message);
                }
                else
                {
                    chat = new ChatWindow(hub, localIdentity, remoteIdentity);
                }
                chatWindows.Add(remoteIdentity, chat);
            }
            chat.Show();
        }

        private ChatWindow GetChatWindowByRemoteClientId(string clientId)
        {
            try
            {
                var window = from a in chatWindows
                             where a.Key.ClientId == clientId
                             select a.Value;
                if (window.Count() == 1)
                {
                    return window.First();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return null;
        }

        public static void ChatWindowClosing(Netfraction.Identity remoteIdentity)
        {
            if (ChatWindowClosed != null)
            {
                ChatWindowClosed(remoteIdentity);
            }
        }
    }
}
